$(function(){
    ckeditor = CKEDITOR.replace("postContent");
    $("input[type='file']").live("change", function(){
        var filename = $(this).val();
        if (filename != null && filename !== "") {
            //$(this).attr("name","file");
            var count = parseInt($("#hiddenValue").val(), 10) + 1;
            $("#hiddenValue").val(count);
            var html = "<tr><th style='width:300px;'><input type='file' name='attach_" + count + "' size='40' id='attach_" + count + "'><span id='localfile_" + count + "'></span><td class='nums'> <input size='10' name='attachcredits_" + count + "' value='0'  id='attachcredits_" + count + "'></td><td>&nbsp;<input size='30' name='attachtitle_" + count + "' maxlength='50' id='attachtitle_" + count + "'> </td></tr>";
            $("#attachbody").append(html);
            $(this).hide();
            count = count - 1;
            var spanHtml = "[&nbsp;<a href='javaScript:void(0)' onclick='removeAttach(this)'>删除</a>&nbsp;] [&nbsp;<a href='javaScript:void(0)' onclick='insertAttr(this)'>插入帖内</a>&nbsp;] <span class='smalltxt'>[" + count + "]</span>" + filename;
            $(this).next().html(spanHtml);
        }
    });
    $("input[id^='attachcredits']").live("change", function(){
        var type = "^\\d+$";
        if ($(this).val().match(type) == null) {
            alert("请输入大于零的整数!");
            $(this).val("0");
        }
        var num = parseInt($(this).val(), 10);
        if (num > 10) {
            alert("不得超过10分!");
            $(this).val("0");
        }
    });
    $("#postbtn").click(function(){
        if (login !== true) {
            alert("游客不得发帖！");
            return false;
        }
        $("#post").val(CKEDITOR.instances.postContent.getData());
    });
    
    $("#form").validate({
        errorPlacement: function(error, element){
            error.appendTo(element.parent());
        },
        rules: {
            "subject": {
                required: true,
                maxlength: 50
            },
            "postContent": {
                required: true,
                minlength: 20
            }
        },
        messages: {
            "subject": {
                required: "标题必填！",
                maxlength: "标题不得超过{0}个字!"
            },
            "postContent": {
                required: "发贴内容必填!",
                minlength: "发帖长度不得短于{0}!"
            }
        }
    });
});
function removeAttach(obj){
    $(obj).parent().parent().parent().remove();
    return false;
}

function insertAttr(obj){
    if ($(obj).parent().text().indexOf(".jpg") == -1) {
        alert("仅支持jpg等格式图片的插入！");
        return;
    }
	var id=$(obj).parent().prev().attr("id");
	var href=$("#"+id).attr("imgSrc");
	if(href==undefined){
	  uploadImages(id);
	}else{
		var title=getTitle(id);
		if(href.indexOf("/upload/")==-1){
			href="/upload/"+href;
		}
		 CKEDITOR.instances.postContent.insertHtml("<img src='"+href+"' title='"+title+"' alt='"+title+"'/>");
	}
   
}
 function uploadImages(id) {
 	 $("#dialog")
        .ajaxStart(function(){
            $(this).dialog("open");
        })//开始上传文件时显示对话框
        .ajaxComplete(function(){
           $(this).dialog("close");
        });//文件上传完成将对话框关闭
      $.ajaxFileUpload({
          //根据updateP得到不同的上传文本的ID
                 url:'/forum/boards/upload',//需要链接到服务器地址
                 secureuri:false,
				 dataType:'text',
                 fileElementId:''+id+'', //文件选择框的id属性（必须）
                 success: function (data, status){
				 	var result=data;
                        if (data != null) {
							var pos=data.indexOf("<div");
							if (pos != -1) {
								result = data.substr(0, pos);
							}
							$("#"+id).attr("imgSrc",result);
							var title=getTitle(id);
						 CKEDITOR.instances.postContent.insertHtml("<img src='"+result+"' title='"+title+"' alt='"+title+"'/>");
						}
						else {
							alert('上传失败');
						} 
                 },
                 error: function (data, status, e){ 
                      alert('上传失败');
                 }
               }
            );

}
function getTitle(id){
	var pos=id.indexOf("_");
	if(pos===-1){
		return "图片";
	}
	var count=id.substr(pos+1);
	var title=$("#attachtitle_"+count).val();
	if (title == null) {
		return "图片";
	}
	return title;
}
function insertSmile(id){
	var src=$("#smile_"+id).attr("src");
	var title=$("#smile_"+id).attr("title");
	var alt=$("#smile_"+id).attr("alt");
	CKEDITOR.instances.postContent.insertHtml("<img src='"+src+"' title='"+title+"' alt='"+alt+"' width='20' height='20' border='0'/>");
}